import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import axios from 'axios'

export const useUserStore = defineStore('user', () => {
  const token = ref(localStorage.getItem('token') || '')
  const user = ref(JSON.parse(localStorage.getItem('user') || '{}'))

  const isLoggedIn = computed(() => !!token.value)
  const isAdmin = computed(() => user.value.role === 'ADMIN')

  // 设置认证头
  const setAuthHeader = () => {
    if (token.value) {
      axios.defaults.headers.common['Authorization'] = `Bearer ${token.value}`
    } else {
      delete axios.defaults.headers.common['Authorization']
    }
  }

  // 登录
  const login = async (credentials) => {
    try {
      const response = await axios.post('/api/auth/login', credentials)
      const { token: newToken, username, role } = response.data
      
      token.value = newToken
      user.value = { username, role }
      
      localStorage.setItem('token', newToken)
      localStorage.setItem('user', JSON.stringify({ username, role }))
      
      setAuthHeader()
      return response.data
    } catch (error) {
      throw error
    }
  }

  // 注册
  const register = async (credentials) => {
    try {
      const response = await axios.post('/api/auth/register', credentials)
      const { token: newToken, username, role } = response.data
      
      token.value = newToken
      user.value = { username, role }
      
      localStorage.setItem('token', newToken)
      localStorage.setItem('user', JSON.stringify({ username, role }))
      
      setAuthHeader()
      return response.data
    } catch (error) {
      throw error
    }
  }

  // 退出登录
  const logout = () => {
    token.value = ''
    user.value = {}
    
    localStorage.removeItem('token')
    localStorage.removeItem('user')
    
    setAuthHeader()
  }

  // 获取当前用户信息
  const getCurrentUser = async () => {
    try {
      const response = await axios.get('/api/auth/me')
      user.value = response.data
      localStorage.setItem('user', JSON.stringify(response.data))
      return response.data
    } catch (error) {
      logout()
      throw error
    }
  }

  // 初始化时设置认证头
  setAuthHeader()

  return {
    token,
    user,
    isLoggedIn,
    isAdmin,
    login,
    register,
    logout,
    getCurrentUser,
    setAuthHeader
  }
})